<script setup lang='ts'>
import { useApplyExport, useApplyIndex } from '@fl/api/add-elevator-api'
import type { applyIndexParam } from '@fl/api/add-elevator-api/model/apply-model'
import { useGetCascadeData } from '@fl/api/elevator-api/verify'
import { SearchForm, SearchTable } from '@fl/components'
import { formatTime } from '@fl/utils'
import { hasPermi } from '@fl/utils/has-permi'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import { reactive } from 'vue'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import applyStep from './components/apply-step.vue'
import createApply from './components/create.vue'
import { useDicts } from './hooks/use-dicts'
import updateNumBox from './components/update-num.vue'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'retrofit-elevator-business-apply',
})
const projectName = ref('')

const tableRef = ref()
const { dicts: { ProgressStatus }, useDict } = useDicts()
const createVisible = ref<boolean>(false)
const applyVisible = ref<boolean>(false)
const applyIsEdit = ref<boolean>(false)
const editId = ref<string>('')
const stepId = ref<string>('')
const status = ref<string>('') // 后端为number，前端用String
const records = ref<any>()
const updateVisible = ref<boolean>(false) // 更新加梯数量
const updateRow = ref<any>()
const positionInfo = ref<any>() // 经纬度信息

// 搜索条件、分页参数
const initialState = {
    updateTime: ['', ''],
    areaCode: '',
    streetCode: '',
    communityCode: '',
    projectId: '',
    building: '',
    unit: '',
}
// const initialState = {} as any
const state = ref<applyIndexParam>(cloneDeep(initialState))
const searchConditions = ref<applyIndexParam>(cloneDeep(initialState))

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

const getAreaOptionsParams = computed(() => ({
    targetLabel: 'area',
}))
const getStreetOptionsParams = computed(() => ({
    areaCode: state.value.areaCode,
    targetLabel: 'street',
}))
const getCommunityOptionsParams = computed(() => ({
    streetCode: state.value.streetCode,
    targetLabel: 'community',
}))
const getProjectOptionsParams = computed(() => ({
    communityCode: state.value.communityCode,
    areaCode: state.value.areaCode,
    streetCode: state.value.streetCode,
    targetLabel: 'project',
    projectName: projectName.value,
}))
const getBuildingOptionsParams = computed(() => ({
    projectId: state.value.projectId,
    targetLabel: 'building',
}))
const getUnitOptionsParams = computed(() => ({
    buildingId:buildingOptions.value && state.value.building
  ? (buildingOptions.value.find(item => item.label === state.value.building)?.buildingId ?? '')
  : '',
    building: state.value.building,
    targetLabel: 'unit',
}))
const { data: areaOptions } = useGetCascadeData(getAreaOptionsParams)
const { data: streetOptions } = useGetCascadeData(getStreetOptionsParams, 'areaCode')
const { data: communityOptions } = useGetCascadeData(getCommunityOptionsParams, 'streetCode')
const { data: projectOptions, isLoading: projectLoading } = useGetCascadeData(getProjectOptionsParams, 'projectName')
const { data: buildingOptions } = useGetCascadeData(getBuildingOptionsParams, 'projectId')
const { data: unitOptions } = useGetCascadeData(getUnitOptionsParams, 'building')
function projectSearch(keyword) {
    projectName.value = keyword
}
watch(() => state.value.areaCode, () => {
    const { building, communityCode, projectId, streetCode, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.streetCode, () => {
    const { building, communityCode, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.communityCode, () => {
    const { building, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.projectId, () => {
    const { building, unit, ...data } = state.value
    state.value = cloneDeep(data)
    console.log(111)
})

watch(() => state.value.building, () => {
    const { unit, ...data } = state.value
    state.value = cloneDeep(data)
})

// 查询列表
const params = computed(() => ({
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityCode: searchConditions.value.communityCode,
    projectId: searchConditions.value.projectId,
    building: searchConditions.value.building,
    unit: searchConditions.value.unit,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    status: searchConditions.value.status,
    applyNo: searchConditions.value.applyNo,
    entranceFlag: searchConditions.value.entranceFlag,
    agentFlag: searchConditions.value.agentFlag,
    startTime: searchConditions.value.updateTime?.[0] ? formatTime(searchConditions.value?.updateTime?.[0], 'yyyy-MM-dd 00:00:00') : '',
    endTime: searchConditions.value.updateTime?.[1] ? formatTime(searchConditions.value?.updateTime?.[1], 'yyyy-MM-dd 23:59:59') : '',
}))
const { data, isLoading } = useApplyIndex(params)

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records)
        tablePage.total = data.value.total!
    }
})

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// 新增（新增没有了，单元的选择未和历史数据的保持统一。create待删）
// function goToAdd() {
//     createVisible.value = true
// }

// 模板下载
function goToDownload() {
    window.open(
        'https://public-obs-cdn.anjulian.com.cn/2025-01-08/a8b42448-dff1-4fad-b378-97fcdffb04bb.docx',
    )
}

// 列表：修改加梯部数
function goUpdateNum(row: any) {
    updateVisible.value = true
    updateRow.value = cloneDeep(row)
}

// 列表：申请步骤
function goNext(row: any, type?: string) {
    stepId.value = String(row.id)
    status.value = String(row.status)
    applyVisible.value = true
    if (type === 'edit') {
        applyIsEdit.value = true
    }
    else {
        applyIsEdit.value = false
    }
    console.log('下一步', status.value, stepId.value)
}

// 列表：编辑（原录入的编辑）
// function goToEdit(row: any) {
//     createVisible.value = true
//     editId.value = String(row.id)
// }

function goToEdit(row: any) {
    console.log('编辑')
    goNext(row, 'edit')
}

// 列表：详情
function goToShow(row: any) {
    positionInfo.value = {
        longitude: Number(row.longitude),
        latitude: Number(row.latitude),
    }
    console.log('详情', row.status, row.id, positionInfo.value)
    goNext(row)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '所在区',
        options: areaOptions as OptionsType,
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '街道',
        options: streetOptions as OptionsType,
        prop: 'streetCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '社区',
        options: communityOptions as OptionsType,
        prop: 'communityCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        // fieldProps: {
        //     filterable: true,
        // },
        label: '小区',
        // options: projectOptions as OptionsType,
        prop: 'projectId',
        // valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '栋',
        options: buildingOptions as OptionsType,
        prop: 'building',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '单元',
        options: unitOptions as OptionsType,
        prop: 'unit',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
            'disabled-date': (time: Date) => {
                return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
            },
        },
        label: '最近更新时间',
        prop: 'updateTime',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 6,
        },
        label: '进度',
        prop: 'status',
        valueType: 'select',
        options: ProgressStatus,
    },
    {
        colProps: {
            span: 6,
        },
        label: '申请编号',
        prop: 'applyNo',
    },
    {
        colProps: {
            span: 6,
        },
        label: '是否平层入户',
        prop: 'entranceFlag',
        valueType: 'select',
        options: [
            {
                label: '是',
                value: 1,
            },
            {
                label: '否',
                value: 2,
            },
        ],
    },
    {
        colProps: {
            span: 8,
        },
        labelWidth: 160,
        label: '是否委托国有代办平台',
        prop: 'agentFlag',
        valueType: 'select',
        options: [
            {
                label: '是',
                value: 1,
            },
            {
                label: '否',
                value: 2,
            },
        ],
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'applyNo', title: '申请编号' },
        { field: 'areaName', title: '区' },
        { field: 'streetName', title: '街道' },
        { field: 'communityName', title: '社区' },
        { field: 'projectName', title: '小区' },
        { field: 'building', slots: { default: 'building' }, title: '栋-单元楼' },
        // { field: 'num', title: '栋数' },
        { field: 'num', title: '加梯部数' },
        { field: 'status', slots: { default: 'status' }, title: '当前进度' },
        { field: 'entranceFlag', slots: { default: 'entranceFlag' }, title: '是否平层入户' },
        { field: 'agentFlag', slots: { default: 'agentFlag' }, title: '是否委托代办平台' },
        // { field: 'agentName', title: '代办平台' },
        { field: 'operaTime', title: '更新时间' },
        { slots: { default: 'operate' }, title: '操作', width: 280 },
    ],
})
// 导出
const exportParams = computed(() => ({
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityCode: searchConditions.value.communityCode,
    projectId: searchConditions.value.projectId,
    building: searchConditions.value.building,
    unit: searchConditions.value.unit,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    status: searchConditions.value.status,
    startTime: searchConditions.value.updateTime?.[0] ? formatTime(searchConditions.value?.updateTime?.[0], 'yyyy-MM-dd 00:00:00') : '',
    endTime: searchConditions.value.updateTime?.[1] ? formatTime(searchConditions.value?.updateTime?.[1], 'yyyy-MM-dd 23:59:59') : '',
}))
const { isPending, mutateAsync } = useApplyExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-model="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        >
            <template #plus-field-projectId>
                <el-select v-model="state.projectId"
                           filterable
                           remote
                           reserve-keyword
                           placeholder="直接搜小区,无需选区域"
                           remote-show-suffix
                           :remote-method="projectSearch"
                           :loading="projectLoading"
                >
                    <el-option v-for="item in projectOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </template>
        </SearchForm>
    </ElCard>

    <ElCard shadow="never">
        <SearchTable ref="tableRef"
                     v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="records"
                     @page-change="handlePageChange"
        >
            <template #status="{ row }">
                {{ useDict('ProgressStatus', row.status) }}
            </template>

            <template #entranceFlag="{ row }">
                <div v-if="row.entranceFlag === 1">
                    是
                </div>

                <div v-else-if="row.entranceFlag === 2">
                    否
                </div>
            </template>

            <template #agentFlag="{ row }">
                <div v-if="row.agentFlag === 1">
                    是
                </div>

                <div v-else-if="row.agentFlag === 2">
                    否
                </div>
            </template>

            <template #building="{ row }">
                {{ row.building }}-{{ row.unit }}
            </template>

            <template #toolbar_buttons>
                <!-- <ElButton type="primary" @click="goToAdd">
                    <div class="i-ic:baseline-add size-16" />
                    录入申请
                </ElButton> -->

                <ElButton type="primary"
                          @click="goToDownload"
                >
                    <div class="i-ic:baseline-add size-16" />
                    模板下载
                </ElButton>

                <ElButton type="primary"
                          plain
                          :loading="isPending"
                          @click="exportData"
                >
                    <div class="i-iconamoon:upload size-16" />
                    导出
                </ElButton>
            </template>

            <template #operate="{ row }">
                <el-button v-if="hasPermi('加装申请-加梯数量')"
                           text
                           type="warning"
                           @click="goUpdateNum(row)"
                >
                    加梯部数
                </el-button>

                <el-button v-if="row.status < 100 && hasPermi('加装申请-处理')"
                           class="small"
                           type="success"
                           text
                           @click="goNext(row, 'edit')"
                >
                    {{ useDict('ProgressButton', row.status) }}
                </el-button>

                <!-- <el-button class="small" type="primary" text @click="goToEdit(row)">
                    编辑
                </el-button> -->

                <el-button v-if="row.status === Number(useDict('ProgressStatus', '补贴到账', false)) && hasPermi('加装申请-处理')"
                           class="small"
                           type="primary"
                           text
                           @click="goToEdit(row)"
                >
                    编辑
                </el-button>

                <el-button text
                           @click="goToShow(row)"
                >
                    详情
                </el-button>
            </template>
        </SearchTable>
    </ElCard>

    <createApply v-model:visible="createVisible"
                 v-model:id="editId"
    />

    <applyStep v-model:visible="applyVisible"
               v-model:isedit="applyIsEdit"
               v-model:id="stepId"
               v-model:status="status"
               v-model:position="positionInfo"
    />

    <updateNumBox v-model:visible="updateVisible"
                  :detail="updateRow"
    />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
